package com.yang.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		System.out.println(req);
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String uri = request.getRequestURI();
		uri = uri.substring(uri.lastIndexOf("/") + 1);
		Map<String,String> map=new HashMap<String, String>();
		map.put("index.jsp","index.jsp");
		map.put("index","index");
		map.put("index.jspx","index.jspx");
		map.put("login.jsp","login.jsp");
		map.put("login","login");
		map.put("reg","reg");
		map.put("reg.jsp","reg.jsp");
		map.put("reg.jspx","reg.jspx");
		map.put("checkname.jspx","checkname.jspx");
		map.put("login.jspx","login.jspx");
		map.put("css","css");
		map.put("js","js");
		map.put("png", "png");
		map.put("gif", "gif");
		String url=uri.substring(uri.lastIndexOf(".")+1);
		/*System.out.println(url);
		System.out.println(uri);*/
		if (map.containsKey(uri)||map.containsKey(url)) {
			chain.doFilter(req, resp);
		}else {
			Object obj = request.getSession().getAttribute("user");
			if (obj == null) {
				response.sendRedirect("index.jsp");
			} else {
				chain.doFilter(req, resp);
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
